/**
 * 
 */
package com.bw.ae.nexus.utils;


import com.bw.ae.nexus.domain.*;

import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.*;

import javax.annotation.PostConstruct;


/**
 * @ClassName: HttpUtil
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author xiaosy
 * @date 2016年8月23日
 *  
 */
@Service
public class HttpUtil {
	@Autowired
	private NexusConfiguration conf;
	@PostConstruct
	public void test()
	{
		System.out.println("####################"+conf.getUrl());
	}

	public synchronized void request(String replaceName,String data) throws IOException {
		try {
			request(URLInfo.CREATEURL.replace("nexusUrl", conf.getUrl()), HttpMethod.POST, Type.CREATE,data);
			request(URLInfo.RUNURL.replace("nexusUrl", conf.getUrl()).replace("?", replaceName), HttpMethod.POST, Type.RUN,null);

		}finally {
			request(URLInfo.REMOVEURL.replace("nexusUrl", conf.getUrl()).replace("?", replaceName), HttpMethod.DELETE, Type.REMOVE,null);
		}

	}

	private void request(String url,HttpMethod method,Type type,String data) throws IOException {
			String auth=new String(Base64.encodeBase64((conf.getUsername() + ":" + conf.getPassword()).getBytes("UTF-8")));
			HttpURLConnection connection=(HttpURLConnection)(new URL(url)).openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Authorization","Basic "+auth);
			connection.setRequestMethod(method.toString());
			switch (type)
			{
				case CREATE:connection.setRequestProperty("Content-Type","application/json");
							break;
				case RUN:connection.setRequestProperty("Content-Type","text/plain");
						break;
				case REMOVE:break;
			}
			connection.connect();
			if(data!=null)
			{
				DataOutputStream out = new DataOutputStream(
						connection.getOutputStream());

				JSONObject jsonObject=JSONObject.fromObject(data);
				out.writeBytes(jsonObject.toString());
				out.flush();
				out.close();
			}
			//读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			System.out.println(sb);
			reader.close();
			// 断开连接
			connection.disconnect();
	}

}
